import {
    assignApiTreeApi,
    assignSaveApi,
    assignTreeApi
} from '@/api/system/role/role'
import { AssignSaveParam, RoleParam } from '@/api/system/role/RoleModel'
import useInstance from '@/hooks/useInstance'
import { StatusCode } from '@/http/request'
import { DialogModel } from '@/types/BaseType'
import { ElTree } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'

export default function useAssignMenu(
    dialogModel: DialogModel,
    onShow: any,
    onClose: any
) {
    const { global } = useInstance()
    // 权限树的ref属性
    const assignTree = ref<InstanceType<typeof ElTree>>()
    // 角色api树的ref属性
    const assignApiTree = ref<InstanceType<typeof ElTree>>()

    const defaultProps = reactive({
        children: 'children',
        label: 'label'
    })

    // 树数据
    const assignTreeData = reactive({
        list: [],
        assignTreeChecked: []
    })

    // api数据
    const assignApiTreeData = reactive({
        list: [],
        assignApiTreeChecked: []
    })

    // 定义分配权限保存参数
    const saveParam = reactive<AssignSaveParam>({
        id: '',
        menu_list: [],
        api_list: []
    })

    const onConfirm = async () => {
        // 获取选中的数据
        let checkedIds = assignTree.value?.getCheckedKeys(false) || []
        if (checkedIds.length == 0) {
            global.$message({ message: '请选择菜单权限', type: 'warning' })
            return false
        }
        // 获取选中的数据
        let checkedApiIds = assignApiTree.value?.getCheckedKeys(false) || []
        // console.log('checkedApiIds=', checkedApiIds)
        if (checkedApiIds.length == 0) {
            global.$message({ message: '请选择API权限', type: 'warning' })
            return false
        }

        // 获取半节点ids
        let hlfIds = assignTree.value?.getHalfCheckedKeys() || []
        saveParam.menu_list = checkedIds?.concat(hlfIds)

        // let apiHlfIds = assignApiTree.value?.getHalfCheckedKeys() || []
        saveParam.api_list = checkedApiIds
        console.log('api_list=', saveParam.api_list)

        // 提交保存
        let res = await assignSaveApi(saveParam)
        if (res && res.code == StatusCode.Success) {
            //信息提示
            global.$message({ message: res.msg, type: 'success' })
            //关闭弹框
            onClose()
        }
    }
    const show = (name: string, roleId: string | number) => {
        assignTreeData.list = []
        assignTreeData.assignTreeChecked = []
        assignApiTreeData.list = []
        assignApiTreeData.assignApiTreeChecked = []

        // 设置权限id
        saveParam.id = roleId
        // 查询权限树的数据
        const param = reactive<RoleParam>({
            id: roleId
        })
        getAssignTree(param)
        getAssignApiTree(param)
        // 设置弹框标题
        dialogModel.title = '为【' + name + '】分配权限'
        // 显示弹框
        onShow()
    }

    // 获取权限树数据
    const getAssignTree = async (param: RoleParam) => {
        let res = await assignTreeApi(param)
        console.log('角色菜单树数据：', res)
        if (res && res.code == StatusCode.Success) {
            assignTreeData.list = res.data.menu_list
            assignTreeData.list.shift()
            assignTreeData.assignTreeChecked = res.data.check_list
            // 数据回显，判断角色原来是否已经分配过权限，如果有，回显
            if (assignTreeData.assignTreeChecked != null) {
                let newArr = reactive([])
                assignTreeData.assignTreeChecked.forEach((item) => {
                    checked(item, assignTreeData.list, newArr)
                })
                // console.log(newArr)
                assignTreeData.assignTreeChecked = newArr
            }
        }
    }

    // 获取角色api树数据
    const getAssignApiTree = async (param: RoleParam) => {
        let res = await assignApiTreeApi(param)
        console.log('角色api树数据：', res)
        if (res && res.code == StatusCode.Success) {
            assignApiTreeData.list = res.data.api_list
            assignApiTreeData.list.shift()
            assignApiTreeData.assignApiTreeChecked = res.data.check_list
            // 数据回显，判断角色原来是否已经分配过权限，如果有，回显
            if (assignApiTreeData.assignApiTreeChecked != null) {
                let newArr = reactive([])
                assignApiTreeData.assignApiTreeChecked.forEach((item) => {
                    checked(item, assignApiTreeData.list, newArr)
                })
                // console.log(newArr)
                assignApiTreeData.assignApiTreeChecked = newArr
            }
        }
    }

    const checked = (id: number, data: any, newArr: any) => {
        data.forEach((item: any) => {
            if (item.id == id) {
                if (item.children == null) {
                    newArr.push(item.id)
                }
            } else {
                if (item.children != null) {
                    //递归调用
                    checked(id, item.children, newArr)
                }
            }
        })
    }

    onMounted(() => {})

    return {
        onConfirm,
        show,
        assignTreeData,
        defaultProps,
        getAssignTree,
        assignTree,
        assignApiTree,
        assignApiTreeData
    }
}
